
<template>
  <el-dialog v-model="isArticlePublishEditorShow" :show-close="false" :fullscreen="true" :close-on-press-escape="false">
    <template #header="{close,titleId,titleClass}">
      <el-affix :offset="20" style="width: 100%">
        <div class="flex h-10 bg-white">
          <h4 class="font-bold">{{isAdd?'写文章':'编辑文章'}}</h4>
          <div class="ml-auto flex">
            <el-button @click="isArticlePublishEditorShow=false">取消</el-button>
            <el-button type="primary" @click="publishArticleSubmit">
              <el-icon class="mr-1" @click="publishArticleSubmit"><Promotion/></el-icon>
              发布
            </el-button>
          </div>
        </div>
      </el-affix>
    </template>
    <!-- label-position="top" 用于指定 label 元素在上面 -->
    <el-form :model="form" ref="publishArticleFormRef" label-position="top" size="large" :rules="rules">
      <el-form-item label="标题" prop="title">
        <el-input v-model="form.title" autocomplete="off" size="large" maxlength="40" show-word-limit clearable/>
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <!-- Markdown 编辑器 -->
        <MdEditor v-model="form.content" @onUploadImg="onUploadImg" editorId="publishArticleEditor"></MdEditor>
      </el-form-item>
      <el-form-item label="封面" prop="cover">
        <el-upload class="avatar-upload" action="#" :on-change="handleCoverChange" :auto-upload="false" :show-file-list="false">
          <img v-if="form.cover" :src="form.cover" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="摘要" prop="summary">
        <!-- :rows="3" 指定 textarea 默认显示 3 行 -->
        <el-input v-model="form.summary" :rows="3" type="textarea" placeholder="请输入文章摘要" />
      </el-form-item>
      <el-form-item label="分类" prop="categoryId">
        <el-select v-model="form.categoryId" clearable placeholder="---请选择---" size="large">
          <el-option v-for="item in categories" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="标签" prop="tags">
        <!-- 标签选择 -->
        <el-select v-model="form.tags" multiple filterable remote reserve-keyword placeholder="---请输入---"
                   remote-show-suffix :remote-method="remoteMethod" allow-create default-first-option
                   :loading="tagSelectLoading" size="large">
          <el-option v-for="item in tags" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
  </el-dialog>

</template>
<script setup>
import {ref,reactive} from "vue";
import {Plus, Promotion} from "@element-plus/icons-vue";
import {MdEditor} from "md-editor-v3";
import {publishArticle,updateArticle} from "@/api/admin/article.js";
import {getCategorySelectList} from "@/api/admin/category.js";
import {searchTags} from "@/api/admin/tag.js";
import 'md-editor-v3/lib/style.css'
import {showModel,showMessage} from "@/composables/utils.js";
import {uploadFile} from "@/api/admin/file.js";


const props= defineProps({
  isAdd: {type: Boolean,default: true }
})
// 是否显示文章发布对话框
const isArticlePublishEditorShow = ref(false)

const open = ()=> isArticlePublishEditorShow.value = true


// 发布文章表单引用
const publishArticleFormRef = ref(null)
// 表单对象
const form = reactive({
  id: null,
  title: '',
  content: '请输入内容',
  cover: '',
  categoryId: null,
  tags: [],
  summary: ""
})

const edit=(detail)=>{
  console.log('當前顯示的數據為',detail)
  form.id = detail.id
  form.title = detail.title
  form.content = detail.content
  form.summary = detail.summary
  form.categoryId = detail.categoryId
  form.summary = detail.summary
  form.tags = detail.tags
  form.cover = detail.cover
  isArticlePublishEditorShow.value=true
}
defineExpose({open,edit})

// 表单校验规则
const rules = {
  title: [
    { required: true, message: '请输入文章标题', trigger: 'blur' },
    { min: 1, max: 40, message: '文章标题要求大于1个字符，小于40个字符', trigger: 'blur' },
  ],
  content: [{ required: true }],
  cover: [{ required: true }],
  categoryId: [{ required: true, message: '请选择文章分类', trigger: 'blur' }],
  tags: [{ required: true, message: '请选择文章标签', trigger: 'blur' }],
}
// 上传文章封面图片
const handleCoverChange= (file)=>{
  let formData = new FormData()
  formData.append('file',file.raw)
  uploadFile(formData).then(e=>{
    // 响参失败，提示错误消息
    if (e.success == false) {
      let message = e.message
      showMessage(message, 'error')
      return
    }

    // 成功则设置表单对象中的封面链接，并提示上传成功
    form.cover = e.data.url
    showMessage('上传成功')
  })
}
// 编辑器图片上传
const onUploadImg = async(files,callback)=>{
  const res = await Promise.all(
      files.map(file=>{
        return new Promise((rev,rej)=>{
          console.log('==> 编辑器开始上传文件...')
          let formData = new FormData()
          formData.append("file", file);
          uploadFile(formData).then((res) => {
            console.log(res)
            console.log('访问路径：' + res.data.url)
            // 调用 callback 函数，回显上传图片
            callback([res.data.url]);
          })
        });
      })
  );
}
// 文章分类
const categories = ref([])
getCategorySelectList().then((res)=>{
  categories.value = res.data
})

// 标签 select Loading 状态，默认不显示
const tagSelectLoading = ref(false)
const tags = ref([])
const remoteMethod = (query)=>{
  if(query){
    tagSelectLoading.value = true
    searchTags(query).then(e=>{
      if(e.success ){
        tags.value = e.data
      }
    }).finally(()=>tableLoading.value = false)
  }
}
remoteMethod()

const emit = defineEmits(['getTableData'])
//
const publishArticleSubmit = ()=>{
  publishArticleFormRef.value.validate((valid)=>{
    if(!valid){
      return false
    }
    if(props.isAdd){
      toPublishArticle()
    }else {
      toEditArticle()
    }

  })
}

const  toPublishArticle=()=>{
  publishArticle(form).then(res=>{

    if (res.success == false) {
      // 获取服务端返回的错误消息
      let message = res.message
      // 提示错误消息
      showMessage(message, 'error')
      return
    }

    showMessage('发布成功')

    cancel()
  })

}

const cancel =()=>{
  // 隐藏发布文章对话框
  isArticlePublishEditorShow.value = false
  // 将 form 表单字段置空
  form.title = ''
  form.content = ''
  form.cover = ''
  form.summary = ''
  form.categoryId = null
  form.tags = []
  // 重新请求分页接口，渲染列表数据
  emit('getTableData')
}

const toEditArticle=()=>{
  updateArticle(form).then(res=>{
    if (res.success == false) {
      // 获取服务端返回的错误消息
      let message = res.message
      // 提示错误消息
      showMessage(message, 'error')
      return
    }

    showMessage('修改成功')

    cancel()
  })
}

</script>


<style scoped>
/* 封面图片样式 */
.avatar-uploader .avatar {
  width: 200px;
  height: 100px;
  display: block;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 200px;
  height: 100px;
  text-align: center;
}
.md-editor-footer {
  height: 40px;
}

/* 指定 select 下拉框宽度 */
.el-select--large {
  width: 600px;
}
</style>
